<template>
	<view class="product">

		<!-- <HeaderNav></HeaderNav> -->

		<view style="z-index:999;position: fixed;">
			<header-bar :isBack="true" title="产品详情" titleTintColor="#000000"  :bgColor="{background: '#ffffff'}" >
				<text slot="back" class="uni_btnIco myicon myicon-zuojiantou" style="" ><</text>
			</header-bar>
		</view>

		<view class="rf-header-box"  :style="{paddingTop: 90 + 'rpx' }">
			<view class="rf-header flex-row" :style="{width:width+'px',height:height+'px'}">
				<!-- 	<view class="rf-back" :style="{marginTop:arrowTop+'px'}" @tap="back">
						<text class="iconfont iconzuo"></text>
					</view> -->
				<view class="input-box"  style="flex:1; min-width:0;" :style="{marginTop:inputTop+'px'}">
					<input
						v-model="keyword"
						@confirm="search"
						placeholder="请输入关键字"
						placeholder-style="font-size: 24upx; color:#ccc;"
						type="text" />
					<text class="icon iconfont iconsousuo2" @tap.stop="search"></text>
				</view>
				<view class="search-ad" :style="{marginTop:inputTop+'px'}">

					<view class="rf-top-item rf-icon-ml" @tap="screen" data-index="3">
						<text>筛选</text>
						<!--<rf-icon name="screen" :size="12" color="#333" rf-icon-class="rf-ml" :bold="true"></rf-icon>-->
					</view>

					<!-- <view class="rf-top-item" @tap="screen" data-index="2">
						<text class="iconfont" :class="isList>0? 'iconliebiaoqiehuan':'iconfenlei'"></text>
					</view> -->

				</view>



			</view>
		</view>

		<rf-product-detail @product="getProductDetail" :userInfo="userInfo" :url="currentUrl" :product="productDetail"></rf-product-detail>

		<!--顶部下拉筛选弹层 属性-->
		<rf-top-drawer bgcolor="#f7f7f7" :show="dropScreenShow" :paddingbtm="110" :translatey="dropScreenH" @close="btnCloseDrop">
			<scroll-view class="rf-scroll-box" scroll-y :scroll-top="scrollTop">
				<view class="rf-seizeaseat-20"></view>
				<view class="rf-drop-item rf-icon-middle" :class="[item.selected?'rf-bold':'']" v-for="(item,index) in attrData" :key="index" @tap.stop="btnSelected" :data-index="index">
					<text class="iconfont icongouxuan" :class="'text-' + themeColor.name" :size="16" :bold="true" v-if="item.selected" rf-icon-class="rf-middle"></text>
					<text class="rf-ml rf-middle">{{item.name}}</text>
				</view>
				<view class="rf-seizeaseat-30"></view>
			</scroll-view>
			<view class="rf-drop-btnbox">
				<view class="rf-drop-btn confirm-btn" :hover-stay-time="150" @tap="reset">重置</view>
				<view class="rf-drop-btn confirm-btn" :hover-stay-time="150" @tap="btnSure">确定</view>
			</view>
		</rf-top-drawer>

		<!--左抽屉弹层 筛选 -->
		<uni-drawer
			class="rf-drawer"
			:visible="drawer"
			mode="right"
			@close="closeDrawer()"
		>
			<view class="rf-drawer-box" :style="{paddingTop:height+'px'}">
				<scroll-view class="rf-drawer-scroll" scroll-y :style="{height:drawerH+'px'}">
					<!-- 保留现有的分类 -->
					<view class="rf-drawer-title">
						<text class="rf-title-bold">产品分类</text>
						<view class="rf-attr-right" :class="'text-' + themeColor.name">
							<text>请选择分类</text>
						</view>
					</view>
					<view class="rf-drawer-content 1111">
						<!-- 树形分类选择器 -->
						<view class="picker-trigger" @tap="showCategoryPicker">
							<text class="picker-text">{{ selectedCategoryPath || '请选择分类' }}</text>
							<text class="picker-arrow">▼</text>
						</view>

						<rf-picker
							ref="categoryPicker"
							:pickerValueArray="categoryOptions"
							v-model="selectedCategoryIndex"
							mode="selector"
							@onConfirm="onCategoryConfirm"
							@onCancel="onCategoryCancel"
							class="tree-picker"
							v-if="categoryOptions.length > 0"
						></rf-picker>

						<!-- 显示当前选择的完整路径 -->
						<view v-if="selectedCategoryPath" class="category-path">
							<text>当前选择: {{ selectedCategoryPath }}</text>
						</view>
					</view>

					<!-- 添加属性筛选部分 -->
					<view class="rf-drawer-title">
						<text class="rf-title-bold">属性筛选</text>
						<view class="rf-attr-right" @tap="toggleSection('attr')">
							<text class="arrow-icon">{{ openSections.attr ? '∧' : '∨' }}</text>
						</view>
					</view>
					<view class="rf-drawer-content" v-show="openSections.attr" style="display: flex; flex-direction: column; width: 100%; padding: 0;">
						<!-- 动态生成规格筛选区块 -->
						<view  v-for="spec in Object.values(specList)" :key="spec.id"
									 class="attr-section" style="width: 100%; display: block;padding:0 20rpx; margin-bottom:20rpx; background:#fff;">
							<view class="attr-header" @tap="toggleSection(spec.id)" style="display: flex; justify-content: space-between; align-items: center; padding: 24rpx; background: #fff5f5;">
								<text style="font-size: 28rpx; color: #333;">{{spec.title}}</text>
								<text style="color: #999; font-size: 24rpx;">{{ expandedSpecId === spec.id ? '收起∧' : '展开∨' }}</text>
							</view>
							<!-- 筛选输入框 -->
							<view v-show="expandedSpecId === spec.id" class="spec-search-container">
								<input
									v-model="specSearchText[spec.id]"
									:placeholder="`搜索${spec.title}...`"
									class="spec-search-input"
									@input="onSpecSearch(spec.id, $event)"
								/>
							</view>
							<view v-show="expandedSpecId === spec.id" style="padding: 20rpx; width: 100%; box-sizing: border-box; background: #fff;">
								<checkbox-group
									style="width: 100%; display: flex; flex-direction: column;"
									@change="(e) => onSpecCheckboxChange(e, spec.id)"
								>
									<label
										v-for="(item, index) in getFilteredSpecValues(spec)"
										v-if="item && item.id"
										:key="item.id"
										:class="{'item-selected': selectedFilters[spec.id] && selectedFilters[spec.id].includes(item.id)}"
										style="display: flex; align-items: center; padding: 20rpx 0; border-bottom: 1px solid #f5f5f5; width: 100%; box-sizing: border-box;"
									>
										<view class="custom-checkbox">
											<checkbox
												:value="item.id"
												:checked="selectedFilters[spec.id] && selectedFilters[spec.id].includes(item.id)"
												style="transform: scale(0.8); opacity: 0; position: absolute;"
											/>
											<view class="checkbox-icon" :class="{'checkbox-selected': selectedFilters[spec.id] && selectedFilters[spec.id].includes(item.id)}">
												<text v-if="selectedFilters[spec.id] && selectedFilters[spec.id].includes(item.id)" class="checkbox-tick">✓</text>
											</view>
										</view>
										<text style="margin-left: 10rpx; font-size: 26rpx; color: #333; flex: 1;">{{ item.title }}</text>
									</label>
								</checkbox-group>
							</view>
						</view>
					</view>

					<view class="rf-safearea-bottom"></view>
				</scroll-view>
				<view class="rf-attr-btnbox">
					<view class="rf-attr-safearea">
						<view class="rf-drawer-btn rf-drawerbtn-black  confirm-btn" @tap="resetAll">重置</view>
						<view class="rf-drawer-btn  confirm-btn" @tap="confirmAll">确定</view>
					</view>
				</view>
			</view>
		</uni-drawer>

		<!--回到顶部-->
		<rf-back-top :scrollTop="scrollTop"></rf-back-top>
		<!-- 404页面 -->
		<view v-if="!productDetail.name && !loading">
			<rf-no-data :custom="true">
				<view class="no-data-title">
					{{ errorInfo || '暂无数据' }}
				</view>
				<view
					@tap="getProductDetail(productDetail.id)"
					slot="refresh"
					class="spec-color"
				>重新加载</view
				>
			</rf-no-data>
		</view>
		<!--顶部下拉菜单-->
		<rf-nav-detail
			@hide="hideNavDetail"
			:popupShow="navDetailShow"
		>
		</rf-nav-detail>
		<!--页面加载动画-->
		<rfLoading isFullScreen :active="loading"></rfLoading>
		<tabBar></tabBar>
	</view>
</template>
<script>
/**
 * @des 商品详情
 *
 * @author stav stavyan@qq.com
 * @date 2020-03-23 15:04
 * @copyright 2019
 */
import HeaderNav from '@/components/header-nav/product.vue';
import HeaderBar from '@/components/header-nav/productNew.vue';
import { productDetail, productCate, productSpec } from '@/api/product';
import rfProductDetail from '@/components/rf-product-detail';
import rfBackTop from '@/components/rf-back-top';
import rfNoData from '@/components/rf-no-data';
import rfTopDrawer from '@/components/rf-top-drawer';
import uniDrawer from '@/components/uni-drawer/drawer';
import rfPicker from '@/components/rf-picker/index.vue';
export default {
	components: {
		rfProductDetail,
		rfBackTop,
		rfNoData,
		HeaderNav,
		HeaderBar,
		rfTopDrawer,
		uniDrawer,
		rfPicker
	},
	data() {
		return {
			cates:{},
			recommends:{},
			productDetail: {},
			loading: true,
			errorInfo: '',
			userInfo: {},
			scrollTop: 0,
			currentUrl: '',
			navDetailShow: false,
			appName: this.$mSettingConfig.appName,
			// 搜索和筛选相关数据
			keyword: '',
			searchKey: "", //搜索关键词
			width: 200, //header宽度
			height: 90, //header高度
			inputTop: 0, //搜索框距离顶部距离
			arrowTop: 0, //箭头距离顶部距离
			dropScreenH: 0, //下拉筛选框距顶部距离
			attrData: [],
			attrIndex: -1,
			dropScreenShow: false,
			tabIndex: 0, //顶部筛选索引
			isList: true, //是否以列表展示  | 列表或大图
			drawer: false,
			drawerH: 0, //抽屉内部scrollview高度
			selectedName: "综合",
			selectH: 0,
			dropdownList: [{
				name: "综合",
				selected: true,
				param: {}
			}, {
				name: "价格升序",
				selected: false,
				param: { price: 'asc' }
			}, {
				name: "价格降序",
				selected: false,
				param: { price: 'desc' }
			}],
			// 筛选相关数据
			minPrice: '',
			maxPrice: '',
			openSections: {
				attr: true
			},
			expandedSpecId: null, // 当前展开的规格ID
			selectedFilters: {
				productClass: [],
				protein: [],
				application: []
			},
			searchText: {
				protein: ''
			},
			specSearchText: {}, // 每个规格的搜索文本
			productClassList: [],
			proteinList: [
				{ id: '1', title: 'Protein A' },
				{ id: '2', title: 'Protein B' },
				{ id: '3', title: 'Protein C' },
				{ id: '4', title: 'Protein D' },
				{ id: '5', title: 'Protein E' }
			],
			applicationList: [
				{ id: '1', title: '检测' },
				{ id: '2', title: '免疫组化' },
				{ id: '3', title: '测序' },
				{ id: '4', title: '流式细胞术' }
			],
			currentCategory: null,
			currentSubcategory: null,
			currentThirdLevelCategory: null,
			categoryDisplayList: [],
			subcategoryDisplayList: [],
			thirdLevelCategoryDisplayList: [],
			hasSubcategories: false,
			hasThirdLevelCategories: false,
			originalCategoryData: [], // 存储原始分类数据
			flattenedCategories: [], // 存储扁平化后的所有分类
			selectedCategoryId: null, // 当前选中的分类ID
			selectedCategoryPath: '', // 当前选中的分类路径
			selectedCategoryTitle: '', // 当前选中的分类标题
			selectedCategoryIndex: [0], // picker当前选中索引
			specList: [], // 规格列表数据
			currentSpecIds: [], // 当前筛选的规格ID列表
			dataLoadStatus: {
				categoryLoaded: false,
				specLoaded: false
			}, // 数据加载状态
			defaultCategoryId: null, // 默认选中的分类ID
			categoryOptions: [] // 分类选择器的选项数组
		};
	},
	created() {
		console.log('测试数据已加载:', this.proteinList, this.applicationList);
		// 初始化数据
		this.initFilterData();
	},
	// #ifndef MP
	onNavigationBarButtonTap(e) {
		const index = e.index;
		if (index === 0) {
			this.navDetailShow = true;
		}
	},
	// #endif
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
	async onLoad(options) {
		this.productId = options.id;
		this.userInfo = uni.getStorageSync('userInfo') || {};

		// 获取系统信息设置header尺寸和抽屉高度
		let obj = {};
		// #ifdef MP-WEIXIN
		obj = wx.getMenuButtonBoundingClientRect();
		// #endif
		// #ifdef MP-BAIDU
		obj = swan.getMenuButtonBoundingClientRect();
		// #endif
		// #ifdef MP-ALIPAY
		my.hideAddToDesktopMenu();
		// #endif
		uni.getSystemInfo({
			success: (res) => {
				this.width = obj.left || res.windowWidth;
				this.height = obj.top ? (obj.top + obj.height + 8) : (res.statusBarHeight + 64);
				this.inputTop = obj.top ? (obj.top + (obj.height - 30) / 2) : (res.statusBarHeight + 7);
				this.arrowTop = obj.top ? (obj.top + (obj.height - 32) / 2) : (res.statusBarHeight + 6);
				//略小，避免误差带来的影响
				this.dropScreenH = this.height * 750 / res.windowWidth + 186;
				this.drawerH = res.windowHeight - uni.upx2px(100) - this.height;
			}
		});

		await this.initData();
	},
	methods: {
		// 搜索功能
		search() {
			if (!this.keyword.trim()) {
				uni.showToast({
					title: '请输入搜索关键字',
					icon: 'none'
				});
				return;
			}
			// 跳转到产品列表页面进行搜索
			this.$mRouter.push({
				route: `/pages/product/list?keyword=${this.keyword}`
			});
		},

		// 筛选功能
		screen(e) {
			let index = parseInt(e.currentTarget.dataset.index, 10);
			if (index === 0) {
				this.showDropdownList();
			} else if (index === 1) {
				let params = {}
				if (this.tabIndex === 1) {
					this.tabIndex = null;
					params.total_sales = 'asc';
				} else {
					this.tabIndex = 1;
					params.total_sales = 'desc';
				}
				// 跳转到产品列表页面进行排序 - 使用 GET 方式传输参数
				const queryString = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
				const url = queryString ? `/pages/product/list?${queryString}` : `/pages/product/list`;
				this.$mRouter.push({
					route: url
				});
			} else if (index === 2) {
				this.isList = !this.isList
			} else if (index === 3) {
				// 确保所有section都可见
				this.openSections.attr = true;
				// 打开抽屉
				this.drawer = true;
			}
		},

		// 显示下拉列表 - 完全按照 list.vue 实现
		showDropdownList() {
			this.selectH = 246;
			this.tabIndex = 0;
		},

		// 隐藏下拉列表
		hideDropdownList() {
			this.selectH = 0
		},

		// 下拉选项点击
		dropdownItem(e) {
			let index = parseInt(e.currentTarget.dataset.index, 10);
			let arr = this.dropdownList;
			for (let i = 0; i < arr.length; i++) {
				if (i === index) {
					arr[i].selected = true;
				} else {
					arr[i].selected = false;
				}
			}
			this.dropdownList = arr;
			this.selectedName = index === 0 ? '综合' : index === 1 ? '价格升序' : '价格降序';
			this.selectH = 0;
			// 跳转到产品列表页面进行筛选 - 使用 GET 方式传输参数
			const params = this.dropdownList[index].param || {};
			const queryString = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
			const url = queryString ? `/pages/product/list?${queryString}` : `/pages/product/list`;
			this.$mRouter.push({
				route: url
			});
		},

		// 关闭下拉筛选 - 完全按照 list.vue 实现
		btnCloseDrop() {
			this.scrollTop = 1;
			this.$nextTick(() => {
				this.scrollTop = 0
			});
			this.dropScreenShow = false;
			this.attrIndex = -1
		},

		// 选择筛选项 - 完全按照 list.vue 实现
		btnSelected(e) {
			let index = e.currentTarget.dataset.index;
			this.$set(this.attrData[index], "selected", !this.attrData[index].selected)
		},

		// 确定筛选 - 按照 list.vue 实现但适配产品详情页
		btnSure() {
			let index = this.attrIndex;
			let arr = this.attrData;
			let active = false;
			let attrName = "";
			let params = {};
			//这里只是为了展示选中效果,并非实际场景
			for (let item of arr) {
				if (item.selected) {
					active = true;
					attrName += attrName ? ";" + item.name : item.name;
					// 收集参数
					if (item.param) {
						params = { ...params, ...item.param };
					}
				}
			}
			this.btnCloseDrop();

			// 跳转到产品列表页面进行筛选 - 使用 GET 方式传输参数
			if (active) {
				const queryString = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
				const url = queryString ? `/pages/product/list?${queryString}` : `/pages/product/list`;
				this.$mRouter.push({
					route: url
				});
			}
		},

		// 重置筛选 - 按照 list.vue 实现但适配产品详情页
		async reset() {
			this.attrIndex = -1;
			for (let i = 0; i < this.attrData.length; i++) {
				this.attrData[i].selected = false;
			}
			// 重置其他筛选状态
			this.minPrice = '';
			this.maxPrice = '';
			// 产品详情页不需要调用 getBrandList 和 getProductCate
		},

		// 确定筛选
		btnSure() {
			this.dropScreenShow = false;
			if (this.attrIndex >= 0) {
				// 跳转到产品列表页面进行筛选 - 使用 GET 方式传输参数
				const params = this.attrData[this.attrIndex].param || {};
				const queryString = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
				const url = queryString ? `/pages/product/list?${queryString}` : `/pages/product/list`;
				this.$mRouter.push({
					route: url
				});
			}
		},

		// 复制商品信息到剪切板
		copyProductInfo(item) {
			// 处理HTML标签：将<br>替换为换行符，去掉其他HTML标签
			const cleanIntro = this.cleanHtmlTags(item.intro_h5 || item.intro || '暂无描述');

			const info = `产品名称：${item.name}\n
			  货号：${item.skustr}\n
			  产品详情地址：https://www.enkilife.cn/h5/#/pages/product/product?id=${item.id}\n
			  产品说明书地址：${item.document || '暂无'}\n
			  商品描述：${cleanIntro}`;



			// const info = `名称：${item.name}\n简介：${item.sketch}\n型号：${item.model || item.sn || item.code || '-'}\n价格：￥${item.price}\n范围：${item.range || '1-1000pg/mL'}\n灵敏度：${item.sensitivity || '35pg/mL'}`;
			// #ifdef H5
			if (navigator && navigator.clipboard && window.isSecureContext) {
				navigator.clipboard.writeText(info).then(() => {
					this.copySuccessDialog = true;
					uni.showToast({ title: '已复制', icon: 'none' });
				}).catch(() => {
					this._fallbackCopyTextToClipboard(info);
				});
			} else {
				this._fallbackCopyTextToClipboard(info);
			}
			// #endif

			// #ifdef MP-WEIXIN || APP-PLUS || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO
			uni.setClipboardData({
				data: info,
				success: () => {
					this.copySuccessDialog = true;
					uni.showToast({ title: '已复制', icon: 'none' });
				},
				fail: () => {
					uni.showToast({ title: '复制失败', icon: 'none' });
				}
			});
			// #endif
		},
		// copyProductInfo(item) {
		// 	  const info = `名称：${item.name}\n简介：${item.sketch}\n型号：${item.model || item.sn || item.code || '-'}\n价格：￥${item.price}\n范围：${item.range || '1-1000pg/mL'}\n灵敏度：${item.sensitivity || '35pg/mL'}`;
		// 	  // #ifdef H5
		// 	  if (navigator && navigator.clipboard) {
		// 	    navigator.clipboard.writeText(info).then(() => {
		// 	      this.copySuccessDialog = true;
		// 	    }, () => {
		// 	      uni.showToast({ title: '复制失败', icon: 'none' });
		// 	    });
		// 	  } else {
		// 	    // 兼容老浏览器
		// 	    const textarea = document.createElement('textarea');
		// 	    textarea.value = info;
		// 	    document.body.appendChild(textarea);
		// 	    textarea.select();
		// 	    try {
		// 	      document.execCommand('copy');
		// 	      this.copySuccessDialog = true;
		// 	    } catch (err) {
		// 	      uni.showToast({ title: '复制失败', icon: 'none' });
		// 	    }
		// 	    document.body.removeChild(textarea);
		// 	  }
		// 	  // #endif

		// 	  // #ifdef MP-WEIXIN || APP-PLUS || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO
		// 	  uni.setClipboardData({
		// 	    data: info,
		// 	    success: () => {
		// 	      this.copySuccessDialog = true;
		// 	    },
		// 	    fail: () => {
		// 	      uni.showToast({ title: '复制失败', icon: 'none' });
		// 	    }
		// 	  });
		// 	  // #endif
		// 	},
		// 隐藏顶部导航
		hideNavDetail() {
			this.navDetailShow = false;
		},
		// 数据初始化
		async initData() {
			if (this.userInfo.promo_code) {
				this.currentUrl = `${this.$mConfig.hostUrl}/pages/product/product?id=${this.productId}&promo_code=${this.userInfo.promo_code}`;
			} else {
				this.currentUrl = `${this.$mConfig.hostUrl}/pages/product/product?id=${this.productId}`;
			}
			this.hasLogin = this.$mStore.getters.hasLogin;

			// 获取分类和规格数据
			this.getProductCate();
			this.getProductSpec();

			await this.getProductDetail();
		},

		// 初始化筛选数据
		initFilterData() {
			// 初始化属性筛选数据
			this.attrData = [
				{ name: '综合', selected: true, param: {} },
				{ name: '价格升序', selected: false, param: { price: 'asc' } },
				{ name: '价格降序', selected: false, param: { price: 'desc' } },
				{ name: '销量排序', selected: false, param: { total_sales: 'desc' } }
			];
		},

		// 获取商品规格列表
		async getProductSpec() {
			await this.$http
				.get(`${productSpec}`)
				.then(r => {
					console.log('规格数据:', r.data);
					if (r.data && r.data.specs) {
						// 1. 先设置规格列表数据
						this.specList = r.data.specs;

						// 2. 初始化所有规格的选中状态和搜索文本
						// 如果是对象，转换为数组进行处理
						const specArray = Object.values(this.specList);
						specArray.forEach(spec => {
							if (spec && spec.id) {
								this.$set(this.selectedFilters, spec.id, []);
								this.$set(this.specSearchText, spec.id, '');
								console.log('初始化规格:', spec.id, spec.title, '值:', spec.value || spec.values);
							}
						});

						// 3. 设置默认选中的规格值
						this.$nextTick(() => {
							// 获取对象的第一个属性的id
							const firstSpec = specArray[0];
							if (firstSpec && firstSpec.id) {
								this.expandedSpecId = firstSpec.id;
								console.log('默认展开第一个规格:', this.expandedSpecId);
							}
						});
					}
				})
				.catch(err => {
					console.error('获取规格数据失败:', err);
				});
		},

		// 获取商品分类列表 - 完全按照 list.vue 实现
		async getProductCate() {
			await this.$http
				.get(`${productCate}`)
				.then(r => {
					console.log('分类数据:', r.data);

					// 检查是否有category字段
					const categoryData = r.data.category || r.data;

					if (categoryData && Array.isArray(categoryData) && categoryData.length > 0) {
						// 重置扁平化数组
						this.flattenedCategories = [];

						// 递归处理分类树，生成扁平化的分类列表
						const processCategoryTree = (categories, level = 0, parentPath = '') => {
							categories.forEach(category => {
								// 生成缩进字符串
								const indent = '　'.repeat(level); // 使用全角空格进行缩进
								const levelPrefix = level > 0 ? '├─ ' : '';

								// 构建显示标题（包含缩进和层级标记）
								const displayTitle = `${indent}${levelPrefix}${category.title}`;

								// 构建完整路径
								const currentPath = parentPath ? `${parentPath} > ${category.title}` : category.title;

								// 添加到扁平化数组
								this.flattenedCategories.push({
									id: category.id,
									title: displayTitle, // 用于显示的标题（包含缩进）
									originalTitle: category.title, // 原始标题
									level: level,
									path: currentPath, // 完整路径
									hasChildren: category.children && category.children.length > 0
								});

								// 处理子分类
								if (category.children && category.children.length > 0) {
									processCategoryTree(category.children, level + 1, currentPath);
								}
							});
						};

						// 开始处理分类树
						processCategoryTree(categoryData);

						console.log('扁平化后的所有分类:', this.flattenedCategories);

						// 设置分类选择器的选项数组 - 完全按照 list.vue 实现
						this.categoryOptions = this.flattenedCategories.map(category => ({
							value: category.id,
							label: category.title,
							path: category.path,
							title: category.title,
							originalTitle: category.originalTitle,
							level: category.level,
							hasChildren: category.hasChildren
						}));

						// 如果有默认分类ID，设置默认选中
						if (this.defaultCategoryId) {
							this.setDefaultSelectedCategory(this.defaultCategoryId);
						}
					} else {
						console.log('没有分类数据或格式不正确');
					}
				})
				.catch(err => {
					console.error('获取分类数据失败:', err);
				});
		},

		// 检查设备类型并跳转
		checkDeviceAndRedirect() {
			// #ifdef H5
			// 判断是否为PC端
			const isPc = this.isPcDevice();

			if (isPc && this.productDetail && this.productDetail.skustr) {
				// 构建外链URL
				const externalUrl = `http://www.enkilife.cn/p/${this.productDetail.skustr}`;
				console.log('检测到PC端访问，跳转到外链:', externalUrl);

				// 跳转到外链
				window.location.href = externalUrl;
			}
			// #endif
		},

		// 判断是否为PC设备
		isPcDevice() {
			// #ifdef H5
			const userAgent = navigator.userAgent.toLowerCase();
			const mobileKeywords = [
				'mobile', 'android', 'iphone', 'ipad', 'ipod',
				'blackberry', 'windows phone', 'opera mini',
				'iemobile', 'wpdesktop'
			];

			// 检查是否包含移动设备关键词
			const isMobile = mobileKeywords.some(keyword => userAgent.includes(keyword));

			// 检查屏幕宽度（PC端通常宽度大于768px）
			const isWideScreen = window.innerWidth > 768;

			// 如果不是移动设备且屏幕较宽，则认为是PC端
			const isPc = !isMobile && isWideScreen;

			console.log('设备检测结果:', {
				userAgent: userAgent,
				isMobile: isMobile,
				screenWidth: window.innerWidth,
				isWideScreen: isWideScreen,
				isPc: isPc
			});

			return isPc;
			// #endif

			// #ifndef H5
			return false;
			// #endif
		},

		// 设置默认选中的分类 - 完全按照 list.vue 实现
		setDefaultSelectedCategory(categoryId) {
			console.log('设置默认选中分类:', categoryId);

			// 在扁平化分类中查找对应的分类
			const targetCategory = this.flattenedCategories.find(cat =>
				cat.id.toString() === categoryId.toString()
			);

			if (targetCategory) {
				console.log('找到目标分类:', targetCategory);

				// 设置选中的分类信息
				this.selectedCategoryId = targetCategory.id;
				this.selectedCategoryPath = targetCategory.path;
				this.selectedCategoryTitle = targetCategory.originalTitle;

				// 设置 picker 的选中索引
				const categoryIndex = this.categoryOptions.findIndex(option =>
					option.value.toString() === categoryId.toString()
				);

				if (categoryIndex !== -1) {
					this.selectedCategoryIndex = [categoryIndex];
					console.log('设置分类选择器索引:', categoryIndex);
				}

				console.log('分类选择完成:', {
					id: this.selectedCategoryId,
					path: this.selectedCategoryPath,
					title: this.selectedCategoryTitle,
					index: this.selectedCategoryIndex
				});
			} else {
				console.log('未找到匹配的分类ID:', categoryId);
			}
		},

		// 获取产品详情
		async getProductDetail() {
			await this.$http
				.get(`${productDetail}`, {
					id: this.productId
				})
				.then(async r => {
					this.loading = false;
					this.cates = r.data.cates;
					this.recommends = r.data.recommends;

					this.productDetail = r.data.model;
					console.log(this.productDetail.name)
					uni.setNavigationBarTitle({ title: this.productDetail.name });

					// 检查设备类型，如果是PC端则跳转到外链
					this.checkDeviceAndRedirect();

					await this.$mHelper.handleWxH5Share(this.appName, r.data.name, this.currentUrl, r.data.picture);
				})
				.catch(err => {
					this.loading = false;
					this.errorInfo = err;
				});
		},
		// 清理HTML标签：将<br>替换为换行符，去掉其他HTML标签
		cleanHtmlTags(htmlString) {
			if (!htmlString) return '';

			// 将<br>、<br/>、<br />等标签替换为换行符
			let cleanText = htmlString.replace(/<br\s*\/?>/gi, '\n');

			// 去掉所有其他HTML标签
			cleanText = cleanText.replace(/<[^>]*>/g, '');

			// 解码HTML实体
			cleanText = cleanText.replace(/&nbsp;/g, ' ');
			cleanText = cleanText.replace(/&lt;/g, '<');
			cleanText = cleanText.replace(/&gt;/g, '>');
			cleanText = cleanText.replace(/&amp;/g, '&');
			cleanText = cleanText.replace(/&quot;/g, '"');
			cleanText = cleanText.replace(/&#39;/g, "'");

			// 清理多余的空白字符，但保留换行符
			cleanText = cleanText.replace(/[ \t]+/g, ' ').trim();

			return cleanText;
		},

		// 关闭抽屉
		closeDrawer() {
			this.drawer = false;
		},

		// 切换展开/收起规格
		toggleSection(specId) {
			// 如果点击的是当前展开的规格，则收起
			if (this.expandedSpecId === specId) {
				this.expandedSpecId = null;
			} else {
				// 否则展开点击的规格
				this.expandedSpecId = specId;
			}
		},

		// 规格复选框变化
		onSpecCheckboxChange(e, specId) {
			const checkedList = e.detail.value;
			this.$set(this.selectedFilters, specId, checkedList);
			console.log(`规格 ${specId} 选择变更:`, checkedList);
		},

		// 获取过滤后的规格值
		getFilteredSpecValues(spec) {
			const searchText = this.specSearchText[spec.id];
			let specValues = spec.value || spec.values || [];

			// 确保 specValues 是数组
			if (!Array.isArray(specValues)) {
				console.warn('规格值不是数组格式:', specValues);
				// 如果是对象，尝试转换为数组
				if (typeof specValues === 'object' && specValues !== null) {
					specValues = Object.values(specValues);
				} else {
					specValues = [];
				}
			}

			if (!searchText || searchText.trim() === '') {
				return specValues;
			}

			return specValues.filter(item => {
				if (!item || typeof item !== 'object') {
					return false;
				}
				const title = item.title || item.name || '';
				return title.toLowerCase().includes(searchText.toLowerCase());
			});
		},

		// 规格搜索
		onSpecSearch(specId, event) {
			const searchText = event.detail.value;
			this.$set(this.specSearchText, specId, searchText);
			console.log(`规格 ${specId} 搜索文本:`, searchText);
		},

		// 显示分类选择器
		showCategoryPicker() {
			if (this.$refs.categoryPicker) {
				this.$refs.categoryPicker.show();
			}
		},

		// 分类选择确认 - 完全按照 list.vue 实现
		onCategoryConfirm(e) {
			console.log('分类选择确认:', e);
			const selectedIndex = e.index[0];
			const selectedOption = this.categoryOptions[selectedIndex];

			if (selectedOption) {
				const categoryId = selectedOption.value;
				this.setDefaultSelectedCategory(categoryId);
				console.log('分类选择完成，ID:', categoryId);
			}
		},

		// 分类选择取消
		onCategoryCancel() {
			console.log('分类选择取消');
		},

		// 重置所有筛选
		resetAll() {
			// 重置价格区间
			this.minPrice = '';
			this.maxPrice = '';

			// 重置分类选择
			this.selectedCategoryId = null;
			this.selectedCategoryPath = '';
			this.selectedCategoryTitle = '';

			// 重置所有规格选择
			Object.keys(this.selectedFilters).forEach(key => {
				this.$set(this.selectedFilters, key, []);
			});

			// 重置搜索文本
			this.searchText = {};
			this.specSearchText = {};
		},

		// 确认筛选
		confirmAll() {
			const params = {};

			// 添加关键字参数（如果存在）
			if (this.keyword && this.keyword.trim()) {
				params.keyword = this.keyword.trim();
			}

			// 添加分类参数
			if (this.selectedCategoryId) {
				params.cate_id = this.selectedCategoryId;
			}

			// 收集所有选中的规格值
			const allSelectedIds = [];
			Object.values(this.selectedFilters).forEach(selectedValues => {
				if (Array.isArray(selectedValues) && selectedValues.length > 0) {
					allSelectedIds.push(...selectedValues);
				}
			});

			// 如果有选中的规格，添加到参数中
			if (allSelectedIds.length > 0) {
				params.spec_ids = allSelectedIds.join(',');
			}

			// 添加价格区间参数（如果需要的话）
			if (this.minPrice) params.min_price = this.minPrice;
			if (this.maxPrice) params.max_price = this.maxPrice;

			console.log('提交筛选参数:', params);

			this.drawer = false;

			// 跳转到产品列表页面进行筛选 - 使用 GET 方式传输参数
			const queryString = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
			const url = queryString ? `/pages/product/list?${queryString}` : `/pages/product/list`;
			this.$mRouter.push({
				route: url
			});
		}
	},
	computed: {
		themeColor() {
			return this.$mStore.getters.themeColor || { name: 'red' };
		},
		filteredProteinList() {
			console.log('过滤蛋白质列表:', this.proteinList, '搜索文本:', this.searchText.protein);
			if (!this.searchText.protein) return this.proteinList;
			return this.proteinList.filter(item =>
				item.title.toLowerCase().includes(this.searchText.protein.toLowerCase())
			);
		},

	},
	watch: {
		specList: {
			handler(newVal) {
				if (newVal && newVal.length > 0 && !this.expandedSpecId) {
					this.expandedSpecId = newVal[0].id;
				}
			},
			immediate: true
		}
	},
	watch: {
		specList: {
			handler(newVal) {
				if (newVal && newVal.length > 0 && !this.expandedSpecId) {
					this.expandedSpecId = newVal[0].id;
				}
			},
			immediate: true
		}
	}
};
</script>
<style scoped lang="scss">
page {
	background: $page-color-base;
}
.rf-header-box {
	width: 100%;
	background: $color-white;
	// position: fixed;
	z-index: 100;
	left: 0;
	top: 0;
	.rf-header {
		display: flex;
		align-items: center;
		flex-wrap: nowrap;
		width: 100%;
		box-sizing: border-box;

		.rf-back {
			margin-left: 8upx;
			height: 32px !important;
			width: 32px !important;
			display: flex;
			justify-content: center;
			align-items: center;
			.iconzuo {
				font-size: $font-lg + 4upx;
				font-weight: 500;
				color: $font-color-dark;
			}
		}
	}
	.input-box {
		flex: 1;
		min-width: 0;
		font-size: 32rpx;
		box-sizing: border-box;
		color: #333;
		display: flex;
		align-items: center;
		overflow: hidden;
		height: 90rpx;
		background: rgba(255,255,255,0.95);
		border-radius: 16rpx;
		position: relative;
		margin: 0 10rpx 0 10rpx;
		box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.15);
		.iconsousuo2 {
			z-index: 100;
			display: flex;
			align-items: center;
			justify-content: center;
			position: absolute;
			top: 0;
			right: 0;
			width: 100rpx;
			height: 90rpx;
			font-size: 36rpx;
			color: #fff;
			background: #e53935;
			border-radius: 0 16rpx 16rpx 0;
			margin: 0;
			padding: 0;
		}
		input {
			width: 100%;
			padding: 0 20rpx;
			height: 90rpx;
			color: #333;
			font-size: 32rpx;
			border: none;
			background: transparent;
			margin: 0;
			line-height: 90rpx;
		}
	}
}

/*顶部下拉选择 属性*/
.rf-scroll-box {
	width: 100%;
	height: 480upx;
	box-sizing: border-box;
	position: relative;
	z-index: 99;
	color: $color-white;
	font-size: 30upx;
	word-break: break-all;
}
.rf-drop-item {
	color: #333;
	height: 80upx;
	font-size: 28upx;
	padding: 20upx 40upx 20upx 40upx;
	box-sizing: border-box;
	display: inline-block;
	width: 50%;
}
.rf-drop-btnbox {
	width: 100%;
	height: 100upx;
	position: absolute;
	left: 0;
	bottom: 0;
	box-sizing: border-box;
	display: flex;
}
.rf-drop-btn {
	width: 50%;
	font-size: 32upx;
	text-align: center;
	height: 100upx;
	line-height: 100upx;
	border: 0;
}
.confirm-btn {
	background-color: #e53935; // 黑色背景
	color: #fff; // 白色文字
}
.rf-dropdownlist {
	width: 100%;
	position: absolute;
	background: $color-white;
	border-bottom-left-radius: 24upx;
	border-bottom-right-radius: 24upx;
	overflow: hidden;
	box-sizing: border-box;
	padding-top: 10upx;
	padding-bottom: 26upx;
	left: 0;
	top: 88upx;
	visibility: hidden;
	transition: all 0.2s ease-in-out;
	z-index: 99;
	.icongouxuan {
		font-size: $font-lg;
		line-height: 88upx;
	}
}
.rf-dropdownlist-show {
	visibility: visible;
}
.rf-dropdownlist-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.6);
	z-index: -1;
	transition: all 0.2s ease-in-out;
	opacity: 0;
	visibility: hidden;
}
.rf-mask-show {
	opacity: 1;
	visibility: visible;
}
.rf-dropdownlist-item {
	color: #333;
	height: 70upx;
	font-size: 28upx;
	padding: 0 40upx;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

/*顶部下拉选择 综合*/
.rf-drawer-box {
	width: 500upx;
	font-size: 24upx;
	overflow: hidden;
	position: relative;
	padding-bottom: 100upx;
}
.rf-drawer-title {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30upx;
	box-sizing: border-box;
	height: 80upx;
}
.rf-title-bold {
	font-size: 26upx;
	font-weight: bold;
	flex-shrink: 0;
}
.rf-location {
	margin-right: 6upx;
}
.rf-attr-right {
	width: 70%;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	text-align: right;
}
.rf-all-box {
	width: 90%;
	white-space: nowrap;
	display: flex;
	align-items: center;
	justify-content: flex-end;
}
.rf-drawer-content {
	padding: 10rpx 20rpx;
	display: flex;
	flex-direction: column;
	width: 100%;
	box-sizing: border-box;
}
.rf-input {
	border: 0;
	height: 64upx;
	border-radius: 32upx;
	width: 45%;
	background: #f7f7f7;
	text-align: center;
	font-size: $font-base;
	color: #333;
}
.rf-phcolor {
	text-align: center;
	color: #b2b2b2;
	font-size: 24upx;
}
.rf-flex-attr {
	flex-wrap: wrap;
	justify-content: flex-start;
}
.rf-attr-item {
	width: 30%;
	height: 64upx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 4upx;
	box-sizing: border-box;
	border-radius: 32upx;
	margin-right: 5%;
	margin-bottom: 5%;
}
.rf-attr-ellipsis {
	white-space: nowrap;
	text-overflow: ellipsis;
	overflow: hidden;
	width: 96%;
	text-align: center;
}
.rf-attr-item:nth-of-type(3n) {
	margin-right: 0%;
}
.rf-attr-btnbox {
	width: 100%;
	position: absolute;
	left: 0;
	bottom: 0;
	box-sizing: border-box;
	padding: 0 30upx;
	background: $color-white;
}
.rf-attr-safearea {

	display: flex;
	align-items: center;
	justify-content: space-between;
	/*padding-bottom: env(safe-area-inset-bottom);*/
}
.rf-safearea-bottom {
	width: 100%;
	height: env(safe-area-inset-bottom);
}
.rf-attr-btnbox::before {
	content: '';
	position: absolute;
	top: 0;
	right: 0;
	left: 0;
	border-top: 1upx solid #eaeef1;
	-webkit-transform: scaleY(0.5);
	transform: scaleY(0.5);
}
.rf-drawer-btn {
	width: 47%;
	text-align: center;
	height: 60upx;
	border-radius: 30upx;
	flex-shrink: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	box-sizing: border-box;
}
.rf-drawerbtn-black {
	border: 1upx solid;
}

.search-ad {
	flex: 0 0 auto;
	display: flex !important;
	flex-direction: row;
	align-items: center;
	justify-content: center;
	width: 100rpx;
	height: 90rpx;
	margin-left: 10rpx;
	padding: 0;
	flex-shrink: 0;
	/* 确保筛选按钮可见且不换行，与input-box对齐 */

	.rf-top-item {
		height: 90rpx;
		line-height: 90rpx;
		padding: 0 20rpx;
		background-color: #e53935;
		border-radius: 16rpx;
		font-size: 28rpx;
		color: #fff;
		white-space: nowrap;
		display: flex;
		align-items: center;
		justify-content: center;
		min-width: 80rpx;
		border: none;
		font-weight: normal;
		box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.15);

		&:hover {
			background-color: #d32f2f;
		}
	}
}

.attr-group {
	margin-bottom: 20rpx;
	background: #fff;

	.attr-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		background: #fff5f5;
		font-size: 28rpx;
	}

	.attr-content {
		padding: 20rpx;
	}
}

.attr-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	border-bottom: 1px solid #f5f5f5;

	&.selected {
		color: #e4393c;
	}

	.check-icon {
		color: #e4393c;
		font-size: 24rpx;
	}
}

.search-box {
	margin-bottom: 20rpx;

	.search-input {
		width: 100%;
		height: 60rpx;
		background: #f5f5f5;
		border-radius: 30rpx;
		padding: 0 20rpx;
		font-size: 26rpx;
	}
}

.arrow-icon {
	font-size: 24rpx;
	color: #999;
}
.attr-section {
	background: #fff;
	margin-bottom: 20rpx;
	width: 100%; /* 确保宽度是100% */
	display: block; /* 确保是块级元素 */
}

.attr-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx;
	background: #fff5f5;
	font-size: 28rpx;
	color: #333;

	.arrow-icon {
		color: #999;
		font-size: 24rpx;
	}
}

.spec-search-container {
	padding: 0 24rpx 15rpx 24rpx;
	background: #fff;
}

.spec-search-input {
	width: 100%;
	height: 60rpx;
	padding: 0 20rpx;
	border: 1px solid #e0e0e0;
	border-radius: 8rpx;
	font-size: 26rpx;
	background: #f9f9f9;
	box-sizing: border-box;

	&:focus {
		border-color: #e53935;
		background: #fff;
	}
}

.attr-content {
	padding: 20rpx;
	width: 100%;
	box-sizing: border-box;
}

.attr-list {
	display: flex;
	flex-direction: column;
}

.attr-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1px solid #f5f5f5;
	width: 100%;
	box-sizing: border-box;

	checkbox {
		transform: scale(0.8);
	}

	.attr-label {
		margin-left: 10rpx;
		font-size: 26rpx;
		color: #333;
		flex: 1;
	}
}

.item-selected {
	background-color: #fff5f5;
}

.item-selected text {
	color: #e4393c !important;
	font-weight: bold;
}

.custom-checkbox {
	position: relative;
	width: 36rpx;
	height: 36rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.checkbox-icon {
	width: 32rpx;
	height: 32rpx;
	border: 1px solid #ccc;
	border-radius: 4rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.checkbox-selected {
	background-color: #e4393c;
	border-color: #e4393c;
}

.checkbox-tick {
	color: white;
	font-size: 24rpx;
	font-weight: bold;
}

.picker-trigger {
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	padding: 0 20rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.picker-text {
	flex: 1;
	text-align: left;
	font-size: 28rpx;
	color: #333;
}

.picker-arrow {
	color: #999;
	font-size: 24rpx;
	margin-left: 10rpx;
}

.category-path {
	margin-top: 20rpx;
	padding: 15rpx;
	background-color: #fff5f5;
	border-radius: 8rpx;
	font-size: 26rpx;
	color: #e4393c;
	border: 1px solid #ffebeb;
	text-align: left;
}
</style>
